using System;

namespace ParserGenerator.Input
{
    [Serializable]
    public sealed class SourceContext
    {
        public SourceDocument Document => Begin.Document;
        public SourceLocation Begin { get; }
        public SourceLocation End { get; }

        public SourceContext(SourceLocation begin, SourceLocation end)
        {
            if (begin.Document != end.Document)
                throw new ArgumentException(SR.BeginEndDiffDoc);
            if (begin.Index > end.Index)
                throw new ArgumentException(SR.BeginEndNotRange);
            Begin = begin;
            End = end;
        }

        public static SourceContext New(SourceLocation begin, SourceLocation end)
        {
            if (begin.Document != end.Document)
                throw new ArgumentException(SR.BeginEndDiffDoc);
            if (begin.Index > end.Index)
                throw new ArgumentException(SR.BeginEndNotRange);
            return new SourceContext(begin, end);
        }

        public SourceContext WithBegin(SourceLocation begin)
        {
            return new SourceContext(begin, End);
        }

        public SourceContext WithEnd(SourceLocation end)
        {
            return new SourceContext(Begin, end);
        }

        public string TryGetSource()
        {
            return Document.TryGetSource(Begin.Index, End.Index);
        }

        public string GetSource()
        {
            return Document.GetSource(Begin.Index, End.Index);
        }

        public sealed override string ToString()
        {
            string str = TryGetSource();
            if (str != null)
                return str;
            return Begin.ToString();
        }
    }
}
